package two_pointer;

/**
 * Created with IntelliJ IDEA.
 * Description: 541. 反转字符串 II
 * User: Li_yizYa
 * Date: 2025/5/12
 * Time: 21:39
 */
public class Solution3 {
    public static void main(String[] args) {
        String s = "abcdefg";
        int k = 2;
        System.out.println(reverseStr(s, k));
    }
    public static String reverseStr(String s, int k) {
        if (s == null || s.length() == 0) {
            return null;
        }
        char[] str = s.toCharArray();
        int index = 0; // 记录反转的起点
        for (int i = 0; i < str.length; i++) {
            if (i - index + 1 == 2 * k) {
                reverse(str, index, index + k - 1);
                index = i + 1;
            }
        }
        if (str.length - index < k) {
            reverse(str, index, str.length - 1);
        } else {
            reverse(str, index, index + k - 1);
        }
        return new String(str);
    }
    public static String reverseStr2(String s, int k) {
        if (s == null || s.length() == 0) {
            return null;
        }
        char[] str = s.toCharArray();
        int index = 0; // 记录反转的起点
        for (int i = 0; i < str.length; i += 2 * k) {
            if (i + k <= str.length) {
                reverse(str, i, i + k - 1);
                continue;
            }
            // 小于 k 个字符
            reverse(str, i, str.length - 1);
        }
        return new String(str);
    }

    private static void reverse(char[] s, int left, int right) {
        if (s == null || s.length == 0 || left >= right) {
            return;
        }
        while (left < right) {
            char tmp = s[left];
            s[left] = s[right];
            s[right] = tmp;
            left++;
            right--;
        }
    }
}
